package web.servlet;

//import com.sun.org.apache.xml.internal.resolver.Catalog;
import domain.Account;
import domain.Cart;
import domain.CartItem;
import domain.Item;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import service.CatelogService;
import service.LogService;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class AddItemToCartServlet extends HttpServlet {

    private static final String CART_FORM = "/WEB-INF/jsp/cart/cart.jsp";

    private LogService logService;
    private CatelogService catelogService;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session = req.getSession();
        Cart cart = (Cart) session.getAttribute("cart");

        String workingItemId = req.getParameter("workingItemId");

        catelogService=new CatelogService();
        Item item=catelogService.getItem(workingItemId);


        boolean isstock=catelogService.isItemInStock(workingItemId);


        cart.addItem(item,isstock);

        session.setAttribute("cart",cart);


        if(req.getParameter("record")!=null&&(Account)session.getAttribute("loginAccount")!=null){
            logService=new LogService();
            Account account=(Account)session.getAttribute("loginAccount");
            String userid=account.getUsername();
            String action=req.getParameter("record")+workingItemId;


            Calendar rightNow = Calendar.getInstance(); // 子类对象
            int year = rightNow.get(Calendar.YEAR);
            int month = rightNow.get(Calendar.MONTH)+1;
            int date= rightNow.get(Calendar.DATE);
            int hour = rightNow.get(Calendar.HOUR_OF_DAY);
            String dates=year+"."+month+"."+date+" "+hour+"h";

            System.out.println(userid+" "+action);
            logService.record(userid,action,dates);

        }




        req.getRequestDispatcher(CART_FORM).forward(req,resp);
    }
}
